package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    ;
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ArticleService apArticleService;

    /**
     * 生成静态化页面并上传到MinIO
     *
     * @param apArticle 文章实体对象
     * @param content   文章内容JSON字符串
     */
    @Async
    @Override
    public void buildArticleToMinio(ApArticle apArticle, String content) {
        if (apArticle == null || apArticle.getId() == null || StringUtils.isBlank(content)) {
            log.error("生成静态页面失败，文章数据不完整");
            return;
        }

        // 输出流
        StringWriter writer = new StringWriter();
        try {
            // 获取FreeMarker模板
            Template template = configuration.getTemplate("article.ftl");

            // 创建数据模型，包含所有需要传递给模板的数据
            Map<String, Object> dataModel = new HashMap<>();

            // 从ApArticle对象中提取数据
            dataModel.put("title", apArticle.getTitle());
            dataModel.put("authorName", apArticle.getAuthorName());
            dataModel.put("publishTime", apArticle.getPublishTime());

            // 处理文章关系数据（假设需要从其他地方获取）
            Map<String, Object> relation = new HashMap<>();
            relation.put("isfollow", false); // 是否关注作者，需要根据实际业务获取
            relation.put("islike", false);   // 是否已点赞
            relation.put("isunlike", false); // 是否已点踩
            relation.put("iscollection", false); // 是否已收藏
            dataModel.put("relation", relation);

            // 处理文章内容
            dataModel.put("content", JSONArray.parseArray(content));

            // 合成HTML
            template.process(dataModel, writer);

            // 上传到MinIO
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8));
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", inputStream);

            // 更新数据库中的静态页面路径
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                    .eq(ApArticle::getId, apArticle.getId())
                    .set(ApArticle::getStaticUrl, path));

        } catch (TemplateException | IOException e) {
            log.error("生成静态页面失败，文章ID：{}，错误信息：{}", apArticle.getId(), e.getMessage(), e);
            throw new RuntimeException("生成静态页面失败", e);
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("关闭StringWriter失败", e);
            }
        }
    }
}
